
Partial Class Budget_BudgetEditDates
    Inherits System.Web.UI.Page

    Dim CurrentBudget As Cdm.DataCore.Budget.Budget

    Public Function GetActiveImage(ByVal isActive As Boolean) As String
        If isActive Then
            Return "~/Images/GreenCheck.gif"
        Else
            Return "~/Images/Blank1x1.gif"
        End If
    End Function


    Public Function GetStatusColor(ByVal statusId As Integer) As String
        Select Case statusId
            Case Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Approved
                Return "green"
            Case Cdm.DataCore.LookupTables.LuSpendingPlanStatus.SpendingPlanStatus.Denied
                Return "red"
            Case Else
                Return "black"
        End Select
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.ErrorSummary.Visible = False
        If Not (Me.IsPostBack) Then
            BindBudgetData()
            BindSpendingPlans()
        End If
    End Sub

    Private Sub BindBudgetData()
        CurrentBudget = Session("EditBudget")
        Dim BudgetInDataBase As Cdm.DataCore.Budget.Budget = Cdm.DataCore.Budget.Budget.Retrieve(CurrentBudget.BudgetId)
        Me.CurrentBudgetDatesLabel.Text = BudgetInDataBase.EffectiveDateDisplay + " - " + BudgetInDataBase.ExpirationDateDisplay
        Me.NewBudgetStartDate.Text = CurrentBudget.EffectiveDate.ToShortDateString()
        Me.NewBudgetEndDate.Text = CurrentBudget.ExpirationDate.ToShortDateString()
    End Sub

    Private Sub BindSpendingPlans()
        Me.SpendingPlansGridView.DataSource = Cdm.DataCore.Budget.SpendingPlanGrid.ListByBudgetId(Me.CurrentBudget.BudgetId)
        Me.SpendingPlansGridView.DataBind()
    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
        Dim validErrors As ArrayList = DatesValid()
        If validErrors.Count > 0 Then
            formError(validErrors)
            Exit Sub
        End If

        Dim trans As New Gentle.Framework.Transaction()

        Try

        
            Dim budgetOverlapString As String = BudgetOverlapsOtherBudgets()
            If Not String.IsNullOrEmpty(budgetOverlapString) Then
                formError(budgetOverlapString)
                Exit Sub
            End If

            For i As Integer = 0 To Me.SpendingPlansGridView.Rows.Count - 1
                Dim spStartDateTextBox As TextBox = CType(SpendingPlansGridView.Rows(i).FindControl("EditStartDateTextBox"), TextBox)
                Dim spEndDateTextBox As TextBox = CType(SpendingPlansGridView.Rows(i).FindControl("EditEndDateTextBox"), TextBox)
                Dim spStartDateEntered As DateTime = Convert.ToDateTime(spStartDateTextBox.Text)
                Dim spEndDateEntered As DateTime = Convert.ToDateTime(spEndDateTextBox.Text)

                Dim spendingplanId As Integer = Convert.ToInt32(SpendingPlansGridView.DataKeys(i).Value)
                Dim updateSpendingPlan As New Cdm.DataCore.Budget.SpendingPlan()
                updateSpendingPlan.SpendingPlanId = spendingplanId
                updateSpendingPlan.StartDate = spStartDateEntered
                updateSpendingPlan.EndDate = spEndDateEntered
                updateSpendingPlan.DateModified = DateTime.Now
                updateSpendingPlan.LastModified = UserAuthorization.CurrentUser().LogonId
                updateSpendingPlan.UpdateSpendingPlanDates(trans)
            Next

            Dim updateBudget As Cdm.DataCore.Budget.Budget = Session("EditBudget")
            updateBudget.EffectiveDate = Convert.ToDateTime(NewBudgetStartDate.Text)
            updateBudget.ExpirationDate = Convert.ToDateTime(NewBudgetEndDate.Text)
            updateBudget.LastModified = UserAuthorization.CurrentUser().LogonId
            updateBudget.DateModified = DateTime.Now
            updateBudget.Persist(trans)
            If Not String.IsNullOrEmpty(updateBudget.ErrorMessage) Then
                Throw New Exception(updateBudget.ErrorMessage)
            End If
            trans.Commit()
            Response.Redirect("Budget.aspx")
        Catch ex As Exception
            trans.Rollback()
            formError(ex.Message)
            Exit Sub
        End Try


    End Sub

    Private Sub formError(ByVal validErrors As ArrayList)
        Me.ErrorSummary.SetErrors(validErrors)
        Me.ErrorSummary.Visible = True
    End Sub

    Private Sub formError(ByVal singleError As String)
        Me.ErrorSummary.SetSingleError(singleError)
        Me.ErrorSummary.Visible = True
    End Sub

    Private Function DatesValid() As ArrayList
        Dim alError As New ArrayList()

        If Not IsDate(Me.NewBudgetStartDate.Text) Then
            alError.Add("Budget Start Date needs to be a valid date.")
        End If

        If Not IsDate(Me.NewBudgetEndDate.Text) Then
            alError.Add("Budget End Date needs to be a valid date.")
        End If

        For i As Integer = 0 To Me.SpendingPlansGridView.Rows.Count - 1
            Dim spStartDate As TextBox = CType(SpendingPlansGridView.Rows(i).FindControl("EditStartDateTextBox"), TextBox)
            Dim spEndDate As TextBox = CType(SpendingPlansGridView.Rows(i).FindControl("EditEndDateTextBox"), TextBox)
            If Not spStartDate Is Nothing Then
                If (Not IsDate(spStartDate.Text)) Or Not IsDate(spEndDate.Text) Then
                    alError.Add("Need valid Spending Plan Start and End Dates in Row " & i.ToString())
                Else
                    Dim startDate As DateTime = Convert.ToDateTime(spStartDate.Text)
                    Dim endDate As DateTime = Convert.ToDateTime(spEndDate.Text)
                    If startDate > endDate Then
                        alError.Add("End Date must not be earlier than start date in Row " & i.ToString())
                    End If
                End If
            End If
        Next
        'If there is an error message at this point then return it.
        'The next step assumes all dates entered are valid.
        If alError.Count > 0 Then
            Return alError
        End If

        If IsDate(NewBudgetEndDate.Text) And IsDate(NewBudgetStartDate.Text) Then
            Dim budgetStartDate As DateTime = Convert.ToDateTime(NewBudgetStartDate.Text)
            Dim budgetEndDate As DateTime = Convert.ToDateTime(NewBudgetEndDate.Text)
            For i As Integer = 0 To Me.SpendingPlansGridView.Rows.Count - 1
                Dim spStartDateTextBox As TextBox = CType(SpendingPlansGridView.Rows(i).FindControl("EditStartDateTextBox"), TextBox)
                Dim spEndDateTextBox As TextBox = CType(SpendingPlansGridView.Rows(i).FindControl("EditEndDateTextBox"), TextBox)
                Dim spStartDateEntered As DateTime = Convert.ToDateTime(spStartDateTextBox.Text)
                Dim spEndDateEntered As DateTime = Convert.ToDateTime(spEndDateTextBox.Text)

                If spEndDateEntered > budgetEndDate Or spStartDateEntered < budgetStartDate Then
                    alError.Add("Spending Plan dates need to be within budget dates - line " & i.ToString())
                End If
            Next
        End If

        Return alError


    End Function


    Private Function BudgetOverlapsOtherBudgets() As String
        Return ""
    End Function
End Class
